var magic_count = 0;
var click_count = 0;
var del_target = false;
var stop_add_line = false;



//to del
//var t_target = true;
//var t_remove3 = true;
//var t_stop = true;
//var del_target = true;
//active_btn();




function click777() {
    var min = 60*(magic_count + 1) - 33;
    var max = 60*(magic_count + 1) - 27;
    if (click_count >= min && click_count <= max) {
        if (0.65 + (click_count - min)*0.5 + Math.random() > 1) {
            magic_count++; 
            selet_magic_tool();
        }
    }
}
function selet_magic_tool() {
    var rate = Math.random();
    if (rate < 0.3) {
        t_target = true;
    }
    else if (rate < 0.6) {
        t_remove3 = true;
    }
    else {
        t_stop = true;
    }
    active_btn();
}
function active_btn() {
    if (t_target && $('.target-empty').length > 0) {
        $('.target-empty').addClass('target').removeClass('target-empty');
    }
    if (t_remove3 && $('.remove3-empty').length > 0) {
        $('.remove3-empty').addClass('remove3').removeClass('remove3-empty');
    }
    if (t_stop && $('.stop-load-empty').length > 0) {
        $('.stop-load-empty').addClass('stop-load').removeClass('stop-load-empty');
    }
}

var colors = ['c1', 'c2', 'c3', 'c4', 'c5', 'c6'];
$('.box-container').on('click', '.box', function(e) {
    var el = e.target;
    if (del_target) {
        del_target = false;
        delSameColor(el);
        return false;
    }
    checkClickBox(el);
    delBoxArray.push(el);
    doDel();
    click777();
    stop_add_line = false; 
});
$('.magic-tools').on('click', '.target', function(e) {
    t_target = false;
    $('.target').addClass('target-empty').removeClass('target');
    del_target = true;
});
$('.magic-tools').on('click', '.remove3', function(e) {
    t_remove3 = false;
    fallBoxBool = true;
    $('.remove3').addClass('remove3-empty').removeClass('remove3');
    for (var i = 0; i < 3; i++) {
        var boxArray = $('.box[row='+i+']');
        for (var j = 0; j < boxArray.length; j++) {
            delBoxArray.push(boxArray[j]);
        };
    };
    doDel();
    fallBoxBool = false;
});
$('.magic-tools').on('click', '.stop-load', function(e) {
    t_stop = false;
    $('.stop-load').addClass('stop-load-empty').removeClass('stop-load');
    stop_add_line = true;
});

$('.pause-layout').on('click', '.start-a', function(e) {
    $('.action-layout').hide();
    $('.pause-layout').hide();
});
$('.pause-layout').on('click', '.stop', function(e) {
   window.location = '/'; 
});
$('.pause-layout').on('click', '.restart', function(e) {
   window.location.reload();
});
$('.stop-layout').on('click', '.reset', function(e) {
   window.location = '/'; 
});
$('.stop-layout').on('click', '.restart', function(e) {
   window.location.reload();
});
function scopeCounter(callback) {
    var scope = angular.element($('.box-container')).scope(); 
    var count = parseInt(scope.count);
    count ++;
    count = count.toString();
    if (count.length < 4) {
        var str = '';
        for (var i = 0; i < 4 - count.length; i++) {
            str += '0';
        };
        count = str + count;
    }
    scope.count = count;
    scope.$apply(callback);
}
$('.tools').on('click', '.pause', function(e) {
    $('.action-layout').show();
    $('.pause-layout').show();
});
function crSelector(c, r) {
    return $('.box[column|='+c+'][row|='+r+']');
}
var delBoxesArray = [];
var delBoxArray = [];
var checkBoxArray = [];
var checkedBoxArray = [];
var fallBox = [];
var fallCheckBox = [];
var fallBoxBool = false;

function fallBoxCheck() {
    fallBoxBool = true;
    function checkFall() {
        if (fallCheckBox.length === 0) {
            if (delBoxesArray.length === 0) return false;
            delBoxArray = delBoxesArray;
            delBoxesArray = [];
            doDel();
            return false;
        }
        var el = fallCheckBox.pop();
        delBoxArray.push(el); 
        checkClickBox(el, checkFall);
    }
    checkFall();
}

function checkFallBox() {
    while(fallBox.length > 0) {
        var el = fallBox.pop();
        el.column = parseInt($(el).attr('column'));
        el.row = parseInt($(el).attr('row'));
        var rows = [];
        rows.push([el.row + 1, el.column]);
        rows.push([el.row - 1, el.column]);
        rows.push([el.row + 2, el.column]);
        rows.push([el.row - 2, el.column]);
        var columns = [];
        columns.push([el.row, el.column + 1]);
        columns.push([el.row, el.column - 1]);
        columns.push([el.row, el.column + 2]);
        columns.push([el.row, el.column - 2]);
        var count = 0;
        while(rows.length > 0 || columns.length > 0){
            if (count > 1) {
                fallCheckBox.push(el);
                break;
            }
            if (rows.length > 0) {
                var pos = rows.shift();
                var box = crSelector(pos[1], pos[0]);

                if (box[0] && box[0].className === el.className) count++;
                count = rows.length === 0 && count !== 2 ? 0 : count;
                continue;
            }
            var pos = columns.shift();
            var box = crSelector(pos[1], pos[0]);

            if (box[0] && box[0].className === el.className) count++;
            count = columns.length === 0 && count !== 2 ? 0 : count;
        }
    }
    if (fallCheckBox.length > 0) fallBoxCheck();
}

function checkClickBox(el, callback) {
    checkedBoxArray.push(el); 
    el.column = parseInt($(el).attr('column'));
    el.row = parseInt($(el).attr('row'));
    var checkArray = [];
    var rows = [el.row];
    var columns = [el.column];
    rows.push(el.row + 1);
    if (el.row > 0) {
        rows.push(el.row - 1);
    }
    if (el.column > 0) {
        columns.push(el.column - 1);
    }
    if (el.column < 3) {
        columns.push(el.column + 1);
    }
    for (var i = 0; i < rows.length; i++) {
        checkArray.push([rows[i], el.column]);
    };
    for (var j = 0; j < columns.length; j++) {
        checkArray.push([el.row, columns[j]]);
    };
    function doCheck(){
        var pos = checkArray.pop();
        var box = crSelector(pos[1], pos[0]);
        var checked = false;
        for (var i = 0; i < checkedBoxArray.length; i++) {
            if (checkedBoxArray[i] === box[0]) {
                checked = true;
                break;
            }
        };
        if (!checked && box[0] && box[0].className === el.className) {
            checkBoxArray.push(box[0]); 
            delBoxArray.push(box[0]);
        }
        if (checkArray.length > 0) return doCheck();
        if (checkBoxArray.length > 0) return checkClickBox(checkBoxArray.pop(), callback);
        checkedBoxArray = [];
        if (callback) {
            if (delBoxArray.length < 3) delBoxArray = [];
            delBoxesArray = delBoxesArray.concat(delBoxArray);
            delBoxArray = [];
            callback();
        }
    };

    doCheck();
}

function doDel(){
    function batch() {
        checkEmpty();
        if (delBoxArray.length === 0) {
            if (stop_add_line) {
                stop_add_line = false;
                return false;
            }
            if (!fallBoxBool) {
                addBoxLine();
                checkHighest();
                fallBoxBool = false;
            }
            return false;
        }
        var delEl = delBoxArray.pop();
        if (delEl && delEl.parentNode) {
            delEl.style['z-index'] = 100;
            $(delEl).animate({"left": "+=5vh"}, 0);
            $(delEl).animate({"bottom": "-=100vh"}, 500, function() {
                delEl.parentNode.removeChild(delEl); 
                click_count++;
                scopeCounter();
                checkEmpty();
            });
        }
        batch();
    }
    batch();
}

function addBoxLine() {
    var boxes = $('.box');
    for (var i = 0; i < boxes.length; i++) {
        var bottom = parseFloat(boxes[i].style.bottom) + 7.5 + 'vh';
        boxes[i].style.bottom = bottom;
        $(boxes[i]).attr('row', parseFloat(bottom) / 7.5);
    };
    for (var j = 0; j < 4; j++) {
        var el = document.createElement('div');
        var random = parseInt(Math.random()*6);
        random = random === 6 ? 5 : random;
        $(el).addClass('box');
        $(el).addClass(colors[random]);
        $(el).css('position', 'absolute');
        $(el).css('left', 7.5*j + 'vh');
        $(el).css('bottom', '0');
        $(el).attr('row', 0);
        $(el).attr('column', j);
        $('.box-container').append(el);
    };
    if (fallBox.length > 0) checkFallBox();
}
function checkEmpty() {
    for (var i = 0; i < 4; i++) {
        var column = $('.box[column|='+i+']');
        for (var j = 0; j < column.length; j++) {
            var normal = parseFloat(column[j].style.bottom) / 7.5;
            column[j].style.bottom = 7.5*(column.length - j - 1) + 'vh';
            if (normal !== column.length - j - 1) {
                fallBox.push(column[j]); 
            }
        };
    };
}
function checkHighest() {
    for (var i = 0; i < 4; i++) {
        var column = $('.box[column|='+i+']');
        if (column.length === 0) return false;
        if (parseFloat(column[0].style.bottom) / 7.5 > 11) {
            $('.action-layout').show();
            $('.stop-layout').show();
            break;
        }
    };
}

function delSameColor(el) {
    var color = el.className.replace('box ','');
    var colors = $('.' + color);
    for (var i = 0; i < colors.length; i++) {
        delBoxArray.push(colors[i]);
    };
    doDel();
}

function init() {
    for (var i = 0; i < 4; i++) addBoxLine();
}
init();

